<template>
  <el-drawer :title="`分配【${role.roleName}】权限`" v-model="visible" :before-close="close" direction="rtl" size="400px" >
    <div v-loading="loading">
      <el-tree :data="menuList"
               :props="{ label: 'menuName', children: 'children' }"
               show-checkbox
               :expand-on-click-node="false"
               check-on-click-node
               ref="treeRef"
               :check-strictly=!checkStrictly
               :default-checked-keys="menuIds"
               node-key="id"
               highlight-current
               :default-expand-all="expandAll"/>
    </div>
    <template #footer>
      <div class="flex space-between flex-center">
        <div>
          <el-checkbox v-model="expandAll" label="展开/收起" size="large" @change="handleExpand"/>
          <el-checkbox v-model="checkStrictly" label="父子联动" size="large" />
        </div>
        <div>
          <el-button :loading="submitting" @click="submitForm" type="primary">提交</el-button>
          <el-button @click="close">取消</el-button>
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="Permission">
import { treeMenu , roleMenuSave } from '@/api/systemApi';
// import { getMenuIdsByRoleId, saveRoleMenu } from '@/api/systemApi';
import { ref, reactive, toRefs } from 'vue';
import {ElMessage} from "element-plus";

const treeRef = ref();

const state = reactive({
  visible: false,
  loading: false, //div load
  role: {}, // 点击的那个角色对象
  menuList: [] ,
  menuIds: [], // 角色拥有的ids
  checked: false, // 是否已全选
  expandAll: true, // 是否已展开
  submitting: false, // 提交中
  checkStrictly: false,
});

const {visible, loading, role, menuList, menuIds, checked, expandAll, submitting , checkStrictly,defaultCheckedKeys} = {...toRefs(state)};

// 导出给父组件调用
defineExpose({
  open
});

const emits = defineEmits(['handleQuery']);

/**
 * 打开窗口
 */
async function open(role) {
  state.loading = !state.loading
  state.role = role;
  state.visible = true;
  await loadMenuList();
  // 查询角色拥有的菜单ids
  await loadRoleMenuIds(role);
}

/**
 * 关闭窗口
 */
function close() {
  if (state.submitting) return;
  state.menuIds = [];
  state.menuList = [];
  state.checked = false;
  state.expandAll = true;
  state.visible = false;
}

/**
 * 查询所有菜单项
 */
async function loadMenuList() {
  try {
    state.loading = true;
    const {data} = await treeMenu();
    state.menuList = data;
  } catch (error) {
  } finally {
    state.loading = false;
  }
}

/**
 * 查询角色原有权限菜单ids
 */
async function loadRoleMenuIds(role) {
  try {
    state.loading = true;
    if(role.sysRoleMenu.length > 0){
      let menuIds = role.sysRoleMenu.map(item => item.menuId);
      state.menuIds = menuIds;
    }
  } catch (error) {
  } finally {
    state.loading = false;
  }
}

/**
 * 展开、收起
 */
function handleExpand() {
  changeTreeNodeStatus(treeRef.value.store.root);
}

/**
 * 递归所有节点将它的子节点展开
 */
function changeTreeNodeStatus(node) {
  // console.log('node', node);
  node.expanded = state.expandAll;
  for (let i=0; i < node.childNodes.length; i++) {
    // 改变节点的自身expanded状态
    node.childNodes[i].expanded = state.expandAll;
    // 查询当前节点是否还有子节点
    if (node.childNodes[i].childNodes.length > 0) {
      // 递归此节点下的N级子节点
      changeTreeNodeStatus(node.childNodes[i]);
    }
  }
}

/**
 * 提交权限数据
 */
async function submitForm() {
  try {
    state.submitting = true;
    // 收集选中的菜单ids
    const checkedMenuIds = treeRef.value.getCheckedKeys();
    console.log('checkedMenuIds', checkedMenuIds);
    let res = await roleMenuSave({id: role.value.id, menuIds:checkedMenuIds});
    if(res.code == 200 && res.data){
      ElMessage.success("分配权限成功");
    }else{
      ElMessage.error("分配权限失败");
    }
    state.submitting = false;
    emits('handleQuery');
    // 关闭弹窗
    close();
  } catch (error) {
  } finally {
    state.submitting = false;
  }
}

</script>



<style lang="scss" scoped>
.custom-tree-node {
  font-size: 14px;
  display: flex;
  align-items: center;
  padding-left: 10px;
}
</style>